package leetcode;

import java.util.*;

class NeighborSum {
    public Map<Integer, List<Integer>> map = new HashMap<>();
    private int len;
    private int[][] grid;
    private final int[][] adj = {
            {-1, 0}, {1, 0}, {0, -1}, {0, 1}
    };
    private final int[][] dia = {
            {-1, -1}, {-1, 1}, {1, -1}, {1, 1}
    };

    public NeighborSum(int[][] grid) {
        this.len = grid.length;
        this.grid = grid;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid.length; j++) {
                List<Integer> list = new ArrayList<>();
                list.add(i);
                list.add(j);
                this.map.put(grid[i][j], list);
            }
        }
    }

    public int adjacentSum(int value) {
        return getSum(value,adj);
    }

    public int diagonalSum(int value) {
        return getSum(value,dia);
    }

    public int getSum(int value, int[][] method) {
        int sum = 0;
        List<Integer> p = map.get(value);
        int x = p.get(0), y = p.get(1);
        for (int[] ints : method) {
            int nx = x+ints[0];
            int ny = y+ints[1];
            if(nx >=0 && nx <len && ny >=0 && ny <len){
                sum += grid[nx][ny];
            }
        }
        return sum;
    }
}
